//复制一下内容到swagger api描述信息中
// @x-response-apikey-token-set {"tokenKey":"response.data.token","apiKey":"ApiKeyAuth"}
const xResponseApiTokenSet = {
    name: 'x-response-apikey-token-set',
    description: '返回数据进行提取后apikey的token设置',
    args: {
        apis: {
            "/api/xxx": {
                method: "POST",
                detail: {},
            }
        },

        token: "",
    },
}
window.addEventListener('DOMContentLoaded', (event) => {
    /*
      Ensure that the DOM is loaded, then add the event listener.
      here we are listenig to 'before-try' event which fires when the user clicks
      on TRY, it then modifies the POST requests by adding a custom header
    */
    const rapidocEl = document.getElementById('the-doc');
    rapidocEl.addEventListener('before-try', (e) => {
        //     console.log("before")
        //     console.log(e)
        //     console.log(rapidocEl)
    });
    rapidocEl.addEventListener('after-try', (e) => {
        if (xResponseApiTokenSet.args.apis.hasOwnProperty(`${document.location.hash.slice(1)}`)) {
            let api = xResponseApiTokenSet.args.apis[`${document.location.hash.slice(1)}`]
            let params = api.detail[xResponseApiTokenSet.name]
            let tmp = undefined
            try {
                // 尝试执行可能会抛出异常的代码
                let response = e.detail.responseBody
                eval("tmp=" + params.tokenKey)
            } catch (error) {
                // 处理异常
                console.log(error.message); // 输出错误信息
                return
            }

            console.log(params.tokenKey, ":", tmp)
            if (tmp !== undefined) {
                // console.log(tmp)
                rapidocEl.setApiKey(params.apiKey, tmp)
            }
        }
    });
    rapidocEl.addEventListener('before-render', (e) => {
        // console.log(e)
        // console.log(e.detail.spec.paths)

        //筛选当前对应plugin的api
        Object.entries(e.detail.spec.paths).forEach(([key, list]) => {
            Object.entries(list).forEach(([method, detail]) => {
                if (detail.hasOwnProperty(xResponseApiTokenSet.name)) {
                    // console.log(key, method, detail);
                    xResponseApiTokenSet.args.apis[`${method}-${key}`] = {
                        method: method,
                        detail: detail,
                    }
                    xResponseApiTokenSet.args.params = detail[xResponseApiTokenSet.name]
                }
            });
        });

        console.log(e)
        Object.entries(e.detail.spec.paths).forEach(([key, list]) => {
            Object.entries(list).forEach(([method, detail]) => {
                // console.log(detail)
                detail.description = detail.description.replaceAll("\n", "<br>")
            });
        });
    });
    rapidocEl.addEventListener('spec-loaded', (e) => {
        // console.log(e)
    });
});
